package com.project.imageinterference.service;

import cn.hutool.core.io.FileUtil;
import com.project.imageinterference.exception.BusinessException;
import com.project.imageinterference.utils.ImageToArrayConverter;
import com.project.imageinterference.utils.MyUtil;
import com.project.imageinterference.vo.Boxes;
import com.project.imageinterference.vo.ImageIdentifyVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * @Description 处理上传的图片
 * @Author cwhao
 * @Date 2025/2/6 下午2:04
 */
@Service
public class ImageService {

    @Value("${remote.api.url}")
    private String remoteApiUrl;

    @Autowired
    private RemoteService remoteService;

    /**
     * 处理上传的图片
     *
     * @param file 上传的图片文件
     * @return 远程接口返回的结果
     * @throws IOException 如果图片处理失败
     */
    public List<ImageIdentifyVO> processImage(MultipartFile file) throws IOException {
        if(file == null){
            throw new BusinessException("上传的图片为空");
        }
        // 获取文件完整路径
        String inputFile = FileUtil.getAbsolutePath(file.getOriginalFilename());
        String fileExtension = MyUtil.getFileExtension(inputFile).toLowerCase();
        // 校验文件扩展名
        if (!fileExtension.equals("jpg") && !fileExtension.equals("png") &&!fileExtension.equals("jpeg")) {
            throw new BusinessException("上传的图片格式不正确，请上传 jpg、png、jpeg 格式图片");
        }
        // 将图片转换为三维数组
        int[][][] imageArray = ImageToArrayConverter.convertTo3DArray(file);

        List<ImageIdentifyVO> JS = null;
        try {
            // 调用远程接口
//            String s = remoteService.callRemoteApi(remoteApiUrl, imageArray);
            // 使用fastjson 解析远程接口返回的结果
//            JS = JSON.parseArray(s, ImageIdentifyVO.class);
            JS = mockData();
        } catch (Exception e) {
            throw new BusinessException("远程接口返回的结果解析失败");
        }
        return JS;
    }

    private List<ImageIdentifyVO> mockData(){
        List<ImageIdentifyVO> mockData = new ArrayList<>();
        Boxes boxes = new Boxes();
        boxes.setXyxy(Arrays.asList(182.1344,162.2373,657.6269,496.5791));
        boxes.setCls(Arrays.asList(3));
        boxes.setConf(Arrays.asList(0.6988));
        ImageIdentifyVO vo1 = new ImageIdentifyVO();
        vo1.setBoxes(Arrays.asList(boxes));
        vo1.setKeypoints("None");
        vo1.setMasks("None");
        vo1.setNames("None");
        mockData.add(vo1);
        return mockData;
    }

    /**
     * 处理上传的图片
     * @param file
     * @return
     * @throws IOException
     */
    public ResponseEntity<String> uploadImageToRemoteServer(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException("上传的图片为空");
        }
        // 将图片转换为Base64格式
        String base64Image = Base64Utils.encodeToString(file.getBytes());

        // 构造请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("expand_boundary_dist", 20);
        requestBody.put("is_show_img", false);
        requestBody.put("image", base64Image);

        // 设置HTTP请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 构造HTTP请求实体
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
        try {
            // 调用远程接口
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(remoteApiUrl, requestEntity, String.class);
            // 返回远程接口的响应
            return ResponseEntity.ok(responseEntity.getBody());
        }catch (Exception e){
            throw new BusinessException("调用算法服务远程接口失败，请检查网络连接或算法服务是否正常");
        }
    }

    public String uploadImageToConvertBase64(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new BusinessException("上传的图片为空");
        }
        return Base64Utils.encodeToString(file.getBytes());
    }
}
